package org.zjt.servletdemo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjt.servletdemo.domain.User;
import org.zjt.servletdemo.service.IUserService;

import java.sql.Connection;
import java.sql.PreparedStatement;

@Service
public class UserService implements IUserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserService2 userService2;

    @Transactional
    @Override
    public void saveUser(User user) throws Exception {

        /**
         * ERROR:
         *
         * 在spring 事务中不能得到数据库连接利用jdbc来操作，这样数据库连接不支持事务的，因为数据库连接connect的autoCommit是true。
         */
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO user (`name`,`age`) VALUES (?,?)");
        preparedStatement.setString(1, user.getName());
        preparedStatement.setInt(2, user.getAge());
        int update = preparedStatement.executeUpdate();


        /*System.out.println(connection);
        int update2 = jdbcTemplate.update("INSERT INTO user (`name`,`age`) VALUES (?,?)", preparedStatement2 -> {
            preparedStatement2.setString(1, user.getName());
            preparedStatement2.setInt(2, user.getAge());
        });*/


        userService2.saveUser(user);


        int i = 1 / 0;
        if (update < 1)
            throw new IllegalArgumentException("更新失败");

        print( user);
    }

    @Override
    public void print(User user) throws Exception {
        System.out.println("print : "+user);
    }
}
